package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ReadBehaviorService;
import com.heima.common.article.HotArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.dtos.NewBehaviorDTO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
@Slf4j
public class ReadBehaviorServiceImpl implements ReadBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        //获取行为实体数据
        Integer UserId = AppThreadLocalUtils.getUser().getId();
        ApBehaviorEntry entry = apBehaviorEntryService.findByUserIdOrEquipmentId(UserId, dto.getEquipmentId());
        if (entry == null) {
            //entry == null 代表 UserId 与 EquipmentId 同时为null
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请使用账户或设备进行登录");
        }
        //获取行为查询条件
        Query query = Query.query(Criteria.where("entryId").is(entry.getId())
                .and("articleId").is(dto.getArticleId()));
        ApReadBehavior readBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        if (readBehavior != null) {
            //查询数据不为空,用户有阅读行为,修改count+1
            mongoTemplate.updateFirst(query, new Update().set("count", readBehavior.getCount() + 1)
                    .set("updatedTime", new Date()), ApReadBehavior.class);
        } else {
            //无阅读行为,保存数据至mongodb,并初始化count=1
            ApReadBehavior behavior = ApReadBehavior.builder().count((short) 1).articleId(dto.getArticleId())
                    .createdTime(new Date()).updatedTime(new Date()).entryId(entry.getId()).build();
            mongoTemplate.save(behavior);
        }
        //向mq发送消息
        NewBehaviorDTO mess = new NewBehaviorDTO();
        mess.setType(NewBehaviorDTO.BehaviorType.VIEWS);
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
        log.info("阅读行为 发送消息 ==>{}", JSON.toJSONString(mess));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
